//
//  LBWebView+Router.m
//  LBWebView
//
//  Created by WuShiHai on 19/5/28.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "LBWebView+Router.h"

@implementation LBWebView (Router)

- (void)callback:(LBWebViewBridge *)message
         content:(NSString *)content {
    NSString *callback = message.callback.length > 0 ? message.callback
        : [NSString stringWithFormat:@"bridge_%@", message.method];
    [self evaluateJavaScript:[NSString stringWithFormat:@"%@(\"%@\", %@)", callback, message.key, content]
           completionHandler:nil];
}

+ (NSString *)matchPathWithPath:(NSString *)path {
    if ([path containsString:@"://"]) {
        return [self matchPathWithURLString:path];
    } else {
        return [path stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/"]];
    }
}

+ (NSString *)matchPathWithURLString:(NSString *)URLString {
    NSArray *urlComponents = [URLString componentsSeparatedByString:@"?"];
    
    NSString *matchUrl = urlComponents.firstObject;
    
    NSURL *URL = [NSURL URLWithString:matchUrl];
    //@[@"lebbay://",@"native/web?token=!"]
    NSString *host = [URL.host containsString:@"."] ? URL.host : @"://";
    NSArray *matchUrlSeparatedStrs = [matchUrl componentsSeparatedByString:host];
    if (matchUrlSeparatedStrs.count == 2) {
        return [matchUrlSeparatedStrs.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/"]];
    }
    return nil;
}

+ (NSDictionary *)userInfoWithPath:(NSString *)path {
    NSArray *urlComponents = [path componentsSeparatedByString:@"?"];
    if (urlComponents.count == 2) {
        __block NSMutableDictionary *userInfo = @{}.mutableCopy;
        NSArray *parameters = [urlComponents.lastObject componentsSeparatedByString:@"&"];
        [parameters enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray *parameter = [obj componentsSeparatedByString:@"="];
            if (parameter.count == 2) {
                [userInfo setObject:parameter.lastObject forKey:parameter.firstObject];
            }
        }];
        return userInfo;
    }
    return nil;
}

@end
